﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using MoreLinq;
using Telerik.Web.UI;

public partial class Default : System.Web.UI.Page
{
    // Author: Otto Neff | webapps-in-action.com
    // DATA OBJECTS ##############################
    public class Car
    {
        public string Id { get; set; }
        public string Brand { get; set; }
        public string Model { get; set; }
    }
    protected static List<Car> Cars
    {
        get
        {
            List<Car> carList = new List<Car>();
            carList.Add(new Car { Brand = "Ford", Model = "Focus", Id = "1" });
            carList.Add(new Car { Brand = "Ford", Model = "Mondeo", Id = "2" });
            carList.Add(new Car { Brand = "Ford", Model = "Fiesta", Id = "3" });
            carList.Add(new Car { Brand = "Ford", Model = "Transit", Id = "4" });
            carList.Add(new Car { Brand = "Ford", Model = "Taunus", Id = "5" });
            carList.Add(new Car { Brand = "Ford", Model = "Ka", Id = "6" });
            carList.Add(new Car { Brand = "Ford", Model = "Street Ka", Id = "7" });
            carList.Add(new Car { Brand = "Ford", Model = "Escort Cabrio", Id = "8" });
            carList.Add(new Car { Brand = "Audi", Model = "A1", Id = "9" });
            carList.Add(new Car { Brand = "Audi", Model = "A4", Id = "10" });
            carList.Add(new Car { Brand = "Audi", Model = "A8", Id = "11" });
            carList.Add(new Car { Brand = "Audi", Model = "A4 Cabrio", Id = "12" });
            carList.Add(new Car { Brand = "Audi", Model = "RS4 Cabrio", Id = "13" });
            carList.Add(new Car { Brand = "Fiat", Model = "Uno", Id = "14" });
            carList.Add(new Car { Brand = "Fiat", Model = "Duo", Id = "15" });
            carList.Add(new Car { Brand = "Fiat", Model = "500", Id = "16" });
            carList.Add(new Car { Brand = "Mercedes", Model = "SL55", Id = "17" });
            carList.Add(new Car { Brand = "Mercedes", Model = "SL55 AMG", Id = "18" });
            carList.Add(new Car { Brand = "Mercedes", Model = "E63 AMG", Id = "19" });
            return carList;
        }
    }
    // WEBSERVICE ##############################
    [WebMethod(EnableSession = true)]
    public static AutoCompleteBoxData GetCars(object context)
    {
        if (HttpContext.Current.Session["objectFound"] != null)
        {
            return null;
        }
        return new AutoCompleteBoxData
        {
            Items = GetCars(
                ((Dictionary<string, object>)context)["Text"].ToString(),
                (HttpContext.Current.Session["currentTokenEntries"] as AutoCompleteBoxEntryCollection)
            ).ToArray()
        };
    }
    // HELPER ##############################
    protected static List<AutoCompleteBoxItemData> GetCars(string searchString, AutoCompleteBoxEntryCollection previousEntries)
    {
        List<AutoCompleteBoxItemData> resultData = new List<AutoCompleteBoxItemData>();
        List<Car> carResults = new List<Car>();
        Random rn = new Random();
        if (previousEntries.Count == 0)
        {
            carResults = Cars.DistinctBy(n => n.Brand).Where(x => x.Brand.ToLower().Contains(searchString.ToLower())).ToList();
            foreach (Car c in carResults)
            {
                Dictionary<string, object> attributes = new Dictionary<string, object>();
                attributes.Add("PhotoId", rn.Next(1, 10));
                resultData.Add(new AutoCompleteBoxItemData { Value = c.Brand, Text = c.Brand, Attributes = attributes });
            }
            foreach (Car c in Cars.Where(x => x.Brand.ToLower().Contains(searchString.ToLower()) || x.Model.ToLower().Contains(searchString.ToLower())).ToList())
            {
                Dictionary<string, object> attributes = new Dictionary<string, object>();
                attributes.Add("PhotoId", rn.Next(1, 10));
                attributes.Add("UniqueId", c.Id);
                resultData.Add(new AutoCompleteBoxItemData { Value = c.Brand + c.Model, Text = c.Brand + " " + c.Model, Attributes = attributes });
            }
        }
        else
        {
            foreach (AutoCompleteBoxEntry entry in previousEntries)
            {
                if (!string.IsNullOrEmpty(entry.Text))
                {
                    carResults.AddRange(Cars.Where(x => x.Brand == entry.Text && x.Model.ToLower().Contains(searchString.ToLower())).ToList());
                }
            }
            if (previousEntries.Count == 1)
            {
                foreach (Car c in carResults)
                {
                    Dictionary<string, object> attributes = new Dictionary<string, object>();
                    attributes.Add("PhotoId", rn.Next(1, 10));
                    attributes.Add("UniqueId", c.Id);
                    resultData.Add(new AutoCompleteBoxItemData { Value = c.Model, Text = c.Model, Attributes = attributes });
                }
            }
        }
        return resultData;
    }
    // EVENTS ##############################
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (radAutoCompleteBox.Entries.Count == 0)
            {
                radAutoCompleteBox.Entries.Insert(0, new AutoCompleteBoxEntry("Audi", "Audi"));
                Session["currentTokenEntries"] = radAutoCompleteBox.Entries;
            }
        }
    }
    protected void radAutoCompleteBox_EntryAdded(object sender, AutoCompleteEntryEventArgs e)
    {
        Session["currentTokenEntries"] = radAutoCompleteBox.Entries;
        foreach (AutoCompleteBoxEntry i in radAutoCompleteBox.Entries)
        {
            if (i.Attributes["UniqueId"] != null)
            {
                txtWorkWith.Text = i.Text + " with ObjectId " + i.Attributes["UniqueId"].ToString();
                HttpContext.Current.Session["objectFound"] = true;
            }
        }
        RadAjaxManager.GetCurrent(this.Page).ResponseScripts.Add("$find('" + (sender as RadAutoCompleteBox).ClientID + "').get_inputElement().focus();");
    }
    protected void radAutoCompleteBox_EntryRemoved(object sender, AutoCompleteEntryEventArgs e)
    {
        Session["currentTokenEntries"] = radAutoCompleteBox.Entries;
        txtWorkWith.Text = "";
        HttpContext.Current.Session["objectFound"] = null;
        RadAjaxManager.GetCurrent(this.Page).ResponseScripts.Add("$find('" + (sender as RadAutoCompleteBox).ClientID + "').get_inputElement().focus();");
    }
}
